<?php
namespace app\api\controller;

use think\Db;
use think\Exception;

class Setting extends BaseController
{
    /**
     * 获取用户设置
     */
    public function getUserSettings()
    {
        $this->checkToken();
        
        $member_id = $this->getUserId();
        
        try {
            $settings = Db::name('member_settings')
                ->where('member_id', $member_id)
                ->find();
            
            if (!$settings) {
                // 创建默认设置
                $default_settings = [
                    'member_id' => $member_id,
                    'notification_push' => 1,
                    'notification_sound' => 1,
                    'notification_vibrate' => 1,
                    'privacy_phone' => 0,
                    'privacy_location' => 1,
                    'auto_login' => 1,
                    'language' => 'zh-cn',
                    'theme' => 'light',
                    'created_at' => date('Y-m-d H:i:s'),
                    'updated_at' => date('Y-m-d H:i:s')
                ];
                
                Db::name('member_settings')->insert($default_settings);
                $settings = $default_settings;
            }
            
            return $this->renderSuccess($settings);
        } catch (Exception $e) {
            return $this->renderError('获取设置失败：' . $e->getMessage());
        }
    }
    
    /**
     * 更新用户设置
     */
    public function updateUserSettings()
    {
        $this->checkToken();
        
        $member_id = $this->getUserId();
        $notification_push = input('notification_push/d', -1);
        $notification_sound = input('notification_sound/d', -1);
        $notification_vibrate = input('notification_vibrate/d', -1);
        $privacy_phone = input('privacy_phone/d', -1);
        $privacy_location = input('privacy_location/d', -1);
        $auto_login = input('auto_login/d', -1);
        $language = input('language/s', '');
        $theme = input('theme/s', '');
        
        try {
            $update_data = ['updated_at' => date('Y-m-d H:i:s')];
            
            if ($notification_push >= 0) {
                $update_data['notification_push'] = $notification_push;
            }
            if ($notification_sound >= 0) {
                $update_data['notification_sound'] = $notification_sound;
            }
            if ($notification_vibrate >= 0) {
                $update_data['notification_vibrate'] = $notification_vibrate;
            }
            if ($privacy_phone >= 0) {
                $update_data['privacy_phone'] = $privacy_phone;
            }
            if ($privacy_location >= 0) {
                $update_data['privacy_location'] = $privacy_location;
            }
            if ($auto_login >= 0) {
                $update_data['auto_login'] = $auto_login;
            }
            if ($language) {
                $update_data['language'] = $language;
            }
            if ($theme) {
                $update_data['theme'] = $theme;
            }
            
            $exists = Db::name('member_settings')
                ->where('member_id', $member_id)
                ->find();
            
            if ($exists) {
                Db::name('member_settings')
                    ->where('member_id', $member_id)
                    ->update($update_data);
            } else {
                $update_data['member_id'] = $member_id;
                $update_data['created_at'] = date('Y-m-d H:i:s');
                Db::name('member_settings')->insert($update_data);
            }
            
            return $this->renderSuccess(['message' => '设置更新成功']);
        } catch (Exception $e) {
            return $this->renderError('更新设置失败：' . $e->getMessage());
        }
    }
    
    /**
     * 获取系统配置
     */
    public function getSystemConfig()
    {
        try {
            $configs = Db::name('system_config')
                ->where('status', 1)
                ->field('config_key, config_value, config_type')
                ->select();
            
            $result = [];
            foreach ($configs as $config) {
                $value = $config['config_value'];
                
                // 根据类型转换值
                switch ($config['config_type']) {
                    case 'int':
                        $value = (int)$value;
                        break;
                    case 'float':
                        $value = (float)$value;
                        break;
                    case 'bool':
                        $value = (bool)$value;
                        break;
                    case 'json':
                        $value = json_decode($value, true);
                        break;
                    default:
                        $value = (string)$value;
                }
                
                $result[$config['config_key']] = $value;
            }
            
            return $this->renderSuccess($result);
        } catch (Exception $e) {
            return $this->renderError('获取系统配置失败：' . $e->getMessage());
        }
    }
    
    /**
     * 获取应用版本信息
     */
    public function getAppVersion()
    {
        $platform = input('platform/s', 'android'); // android, ios
        
        try {
            $version = Db::name('app_version')
                ->where([
                    'platform' => $platform,
                    'status' => 1
                ])
                ->order('version_code desc')
                ->find();
            
            if (!$version) {
                return $this->renderError('版本信息不存在');
            }
            
            return $this->renderSuccess($version);
        } catch (Exception $e) {
            return $this->renderError('获取版本信息失败：' . $e->getMessage());
        }
    }
    
    /**
     * 检查应用更新
     */
    public function checkUpdate()
    {
        $platform = input('platform/s', 'android');
        $current_version = input('current_version/s', '');
        
        if (!$current_version) {
            return $this->renderError('当前版本号不能为空');
        }
        
        try {
            $latest_version = Db::name('app_version')
                ->where([
                    'platform' => $platform,
                    'status' => 1
                ])
                ->order('version_code desc')
                ->find();
            
            if (!$latest_version) {
                return $this->renderError('版本信息不存在');
            }
            
            $has_update = version_compare($latest_version['version_name'], $current_version, '>');
            
            $result = [
                'has_update' => $has_update,
                'latest_version' => $latest_version,
                'current_version' => $current_version
            ];
            
            return $this->renderSuccess($result);
        } catch (Exception $e) {
            return $this->renderError('检查更新失败：' . $e->getMessage());
        }
    }
    
    /**
     * 获取帮助文档
     */
    public function getHelpDocs()
    {
        $category = input('category/s', '');
        $page = input('page/d', 1);
        $limit = input('limit/d', 10);
        
        try {
            $where = ['status' => 1];
            
            if ($category) {
                $where['category'] = $category;
            }
            
            $docs = Db::name('help_docs')
                ->where($where)
                ->field('doc_id, title, category, summary, sort, created_at')
                ->order('sort asc, created_at desc')
                ->paginate($limit, false, ['page' => $page]);
            
            $result = [
                'data' => $docs->items(),
                'total' => $docs->total(),
                'page' => $page,
                'limit' => $limit,
                'pages' => $docs->lastPage()
            ];
            
            return $this->renderSuccess($result);
        } catch (Exception $e) {
            return $this->renderError('获取帮助文档失败：' . $e->getMessage());
        }
    }
    
    /**
     * 获取帮助文档详情
     */
    public function getHelpDocDetail()
    {
        $doc_id = input('doc_id/d', 0);
        
        if (!$doc_id) {
            return $this->renderError('文档ID不能为空');
        }
        
        try {
            $doc = Db::name('help_docs')
                ->where([
                    'doc_id' => $doc_id,
                    'status' => 1
                ])
                ->find();
            
            if (!$doc) {
                return $this->renderError('文档不存在');
            }
            
            // 增加浏览次数
            Db::name('help_docs')
                ->where('doc_id', $doc_id)
                ->setInc('view_count');
            
            return $this->renderSuccess($doc);
        } catch (Exception $e) {
            return $this->renderError('获取文档详情失败：' . $e->getMessage());
        }
    }
    
    /**
     * 获取常见问题
     */
    public function getFAQ()
    {
        $category = input('category/s', '');
        $keyword = input('keyword/s', '');
        $page = input('page/d', 1);
        $limit = input('limit/d', 10);
        
        try {
            $where = ['status' => 1];
            
            if ($category) {
                $where['category'] = $category;
            }
            
            $query = Db::name('faq')->where($where);
            
            if ($keyword) {
                $query->where('question|answer', 'like', '%' . $keyword . '%');
            }
            
            $faqs = $query->field('faq_id, question, answer, category, sort, created_at')
                ->order('sort asc, created_at desc')
                ->paginate($limit, false, ['page' => $page]);
            
            $result = [
                'data' => $faqs->items(),
                'total' => $faqs->total(),
                'page' => $page,
                'limit' => $limit,
                'pages' => $faqs->lastPage()
            ];
            
            return $this->renderSuccess($result);
        } catch (Exception $e) {
            return $this->renderError('获取常见问题失败：' . $e->getMessage());
        }
    }
    
    /**
     * 清除缓存
     */
    public function clearCache()
    {
        $this->checkToken();
        
        try {
            // 清除应用缓存
            \think\Cache::clear();
            
            // 清除模板缓存
            $temp_path = RUNTIME_PATH . 'temp/';
            if (is_dir($temp_path)) {
                $this->deleteDir($temp_path);
            }
            
            // 清除日志缓存
            $log_path = RUNTIME_PATH . 'log/';
            if (is_dir($log_path)) {
                $files = glob($log_path . '*.log');
                foreach ($files as $file) {
                    if (filemtime($file) < strtotime('-7 days')) {
                        unlink($file);
                    }
                }
            }
            
            return $this->renderSuccess(['message' => '缓存清除成功']);
        } catch (Exception $e) {
            return $this->renderError('清除缓存失败：' . $e->getMessage());
        }
    }
    
    /**
     * 递归删除目录
     */
    private function deleteDir($dir)
    {
        if (!is_dir($dir)) {
            return false;
        }
        
        $files = array_diff(scandir($dir), ['.', '..']);
        foreach ($files as $file) {
            $path = $dir . DIRECTORY_SEPARATOR . $file;
            is_dir($path) ? $this->deleteDir($path) : unlink($path);
        }
        
        return rmdir($dir);
    }
}